﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using IKEA.FileExchange.Domain.FilePackage;
using IKEA.FileExchange.Domain;

public partial class services_DownloadFilesByManager : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;

        Guid packageId = new Guid(context.Request.QueryString["p"]);
        Guid fileId = new Guid(context.Request.QueryString["f"]);

        

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite spSite = new SPSite(context.Request.Url.AbsoluteUri))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    FilePackageInformation packageInfo = FilePackageInformationProvider.GetByUniqueId(packageId);

                    if (packageInfo != null)
                    {
                        SPDocumentLibrary store = null;

                        if (packageInfo.IsConfidential)
                        {
                            store = IKEAFileStoreHelper.GetConfidentialFileStore(spWeb);
                        }
                        else
                        {
                            store = IKEAFileStoreHelper.GetPublicFileStore(spWeb);
                        }

                        SPListItem file = store.GetItemByUniqueId(fileId);

                        if (file != null)
                        {
                            context.Response.Clear();

                            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.File.Name);

                            context.Response.ContentType = "application/octet-stream";

                            using (System.IO.Stream fileStream = file.File.OpenBinaryStream())
                            {
                                using (System.IO.StreamReader sr = new System.IO.StreamReader(fileStream))
                                {
                                    string data = sr.ReadToEnd();

                                    context.Response.Write(data);
                                }
                            }
                        }
                    }
                }
            }
        }
        );
        
        
                
    }
}
